import React, { useState } from "react";
import {
  Modal,
  Form,
  Input,
  Select,
  InputNumber,
  Button,
  Space,
  message,
  Spin,
  Alert,
  List,
  Tag,
  Card,
} from "antd";
import {
  RobotOutlined,
  BulbOutlined,
  CheckCircleOutlined,
} from "@ant-design/icons";
import {
  aiService,
  type AIQuestionGenerationRequest,
} from "../../../../services/ai";
import type { Question } from "../../../../services/examService";

const { TextArea } = Input;
const { Option } = Select;

interface AIGenerationModalProps {
  visible: boolean;
  onCancel: () => void;
  onSuccess: (questions: any[]) => void;
}

const AIGenerationModal: React.FC<AIGenerationModalProps> = ({
  visible,
  onCancel,
  onSuccess,
}) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [generatedQuestions, setGeneratedQuestions] = useState<any[]>([]);

  // 处理AI生成
  const handleGenerate = async (values: any) => {
    setLoading(true);
    try {
      const request: AIQuestionGenerationRequest = {
        topic: values.topic,
        count: values.count,
        type: values.type,
        difficulty: values.difficulty,
        requirements: values.requirements,
        knowledgePoints: values.knowledgePoints,
        targetGrade: values.targetGrade,
      };

      // 使用新的专用接口，避免与智能组卷功能冲突
      const response = await aiService.generateQuestionsWithDedicatedAPI(request);

      if (response.questions && response.questions.length > 0) {
        // 使用真实的AI生成结果，转换为与主页面兼容的格式
        const realQuestions: any[] = response.questions.map((q: any, index: number) => ({
          id: q.id || `ai_${Date.now()}_${index}`,
          type: q.type || values.type,
          difficulty: q.difficulty || 
            (values.difficulty === "easy" ? "easy" : 
             values.difficulty === "medium" ? "medium" : "hard"),
          score: q.score || 
            (values.type === "choice" ? 5 : 
             values.type === "programming" ? 20 : 10),
          content: q.topic || q.content || `AI生成的${values.topic}相关题目内容 ${index + 1}`,
          answer: q.answer || `标准答案 ${index + 1}`,
          knowledge: [q.knowledgePoint || 
            values.knowledgePoints?.[0] || `${values.topic}基础知识`],
          options: q.options || 
            (values.type === "choice" ? ["选项A", "选项B", "选项C", "选项D"] : undefined),
          analysis: q.analysis || q.parse || `这是一道关于${values.topic}的${values.difficulty}难度题目`,
          tags: [],
          createTime: new Date().toISOString(),
          updateTime: new Date().toISOString(),
        }));

        setGeneratedQuestions(realQuestions);
        message.success(`AI成功生成 ${realQuestions.length} 道题目！`);
      } else {
        message.warning("AI生成题目失败，请检查参数或稍后重试");
      }
    } catch (error) {
      console.error("AI生成失败:", error);
      message.error("AI生成失败，请检查网络连接或稍后重试");
    } finally {
      setLoading(false);
    }
  };

  // 确认使用生成的题目
  const handleConfirm = () => {
    if (generatedQuestions.length > 0) {
      onSuccess(generatedQuestions);
      handleCancel();
    }
  };

  // 取消并重置
  const handleCancel = () => {
    form.resetFields();
    setGeneratedQuestions([]);
    onCancel();
  };

  return (
    <Modal
      title={
        <Space>
          <RobotOutlined />
          <span>AI智能生成题目</span>
        </Space>
      }
      open={visible}
      onCancel={handleCancel}
      width={800}
      footer={
        generatedQuestions.length > 0
          ? [
              <Button key="cancel" onClick={handleCancel}>
                取消
              </Button>,
              <Button key="regenerate" onClick={() => form.submit()}>
                重新生成
              </Button>,
              <Button
                key="confirm"
                type="primary"
                icon={<CheckCircleOutlined />}
                onClick={handleConfirm}
              >
                使用这些题目
              </Button>,
            ]
          : [
              <Button key="cancel" onClick={handleCancel}>
                取消
              </Button>,
              <Button
                key="generate"
                type="primary"
                icon={<RobotOutlined />}
                loading={loading}
                onClick={() => form.submit()}
              >
                开始生成
              </Button>,
            ]
      }
    >
      <div>
        <Alert
          message="AI智能生成提示"
          description="请详细描述您的需求，AI将根据您的要求生成高质量的题目。生成过程可能需要1-2分钟。"
          type="info"
          style={{ marginBottom: 24 }}
        />

        {generatedQuestions.length > 0 && (
          <Alert
            message="题目生成完成"
            description="点击'使用这些题目'将自动将这些AI生成的题目添加到您的题库中，您可以在题库中查看和管理这些题目。"
            type="success"
            style={{ marginBottom: 24 }}
            showIcon
          />
        )}

        <Form
          form={form}
          layout="vertical"
          onFinish={handleGenerate}
          initialValues={{
            count: 5,
            type: "choice",
            difficulty: "medium",
            targetGrade: "大二",
          }}
        >
          <Form.Item
            name="topic"
            label="题目主题"
            rules={[{ required: true, message: "请输入题目主题" }]}
          >
            <Input
              placeholder="如：操作系统、数据结构、React开发等"
              prefix={<BulbOutlined />}
            />
          </Form.Item>

          <Space.Compact style={{ width: "100%", marginBottom: 16 }}>
            <Form.Item
              name="count"
              label="生成数量"
              style={{ width: "33%" }}
              rules={[{ required: true, message: "请选择生成数量" }]}
            >
              <InputNumber
                min={1}
                max={20}
                style={{ width: "100%" }}
                placeholder="题目数量"
              />
            </Form.Item>

            <Form.Item
              name="type"
              label="题目类型"
              style={{ width: "33%" }}
              rules={[{ required: true, message: "请选择题目类型" }]}
            >
              <Select placeholder="选择类型">
                <Option value="choice">选择题</Option>
                <Option value="programming">编程题</Option>
                <Option value="analysis">分析题</Option>
              </Select>
            </Form.Item>

            <Form.Item
              name="difficulty"
              label="难度等级"
              style={{ width: "34%" }}
              rules={[{ required: true, message: "请选择难度等级" }]}
            >
              <Select placeholder="选择难度">
                <Option value="easy">简单</Option>
                <Option value="medium">中等</Option>
                <Option value="hard">困难</Option>
              </Select>
            </Form.Item>
          </Space.Compact>

          <Form.Item name="targetGrade" label="目标年级">
            <Select placeholder="选择目标年级">
              <Option value="大一">大一</Option>
              <Option value="大二">大二</Option>
              <Option value="大三">大三</Option>
              <Option value="大四">大四</Option>
            </Select>
          </Form.Item>

          <Form.Item name="knowledgePoints" label="知识点">
            <Select mode="tags" placeholder="请输入相关知识点">
              <Option value="基础概念">基础概念</Option>
              <Option value="算法设计">算法设计</Option>
              <Option value="数据结构">数据结构</Option>
              <Option value="系统设计">系统设计</Option>
              <Option value="编程实践">编程实践</Option>
            </Select>
          </Form.Item>

          <Form.Item name="requirements" label="特殊要求">
            <TextArea
              rows={3}
              placeholder="请描述特殊要求，如：注重实践性、包含代码示例等"
            />
          </Form.Item>
        </Form>

        {loading && (
          <div style={{ textAlign: "center", padding: "20px 0" }}>
            <Spin size="large" />
            <div style={{ marginTop: 16 }}>AI正在生成题目，请稍候...</div>
          </div>
        )}

        {generatedQuestions.length > 0 && (
          <div style={{ marginTop: 24 }}>
            <Alert
              message={`已生成 ${generatedQuestions.length} 道题目`}
              type="success"
              style={{ marginBottom: 16 }}
            />
            <List
              dataSource={generatedQuestions}
              renderItem={(question, index) => (
                <Card
                  key={question.id}
                  size="small"
                  style={{ marginBottom: 8 }}
                  title={
                    <Space>
                      <Tag color="blue">{question.type}</Tag>
                      <Tag color="green">{question.difficulty === 1 ? "简单" : question.difficulty === 2 ? "中等" : "困难"}</Tag>
                      <span>{question.title}</span>
                    </Space>
                  }
                >
                  <div style={{ marginBottom: 8 }}>
                    <strong>题目内容：</strong>
                    <div style={{ marginTop: 4 }}>{question.content}</div>
                  </div>
                  {question.options && (
                    <div style={{ marginBottom: 8 }}>
                      <strong>选项：</strong>
                      <div style={{ marginTop: 4 }}>
                        {question.options.map((option: string, i: number) => (
                          <div key={i}>{String.fromCharCode(65 + i)}. {option}</div>
                        ))}
                      </div>
                    </div>
                  )}
                  <div style={{ marginBottom: 8 }}>
                    <strong>答案：</strong>
                    <div style={{ marginTop: 4 }}>{question.answer}</div>
                  </div>
                  {question.analysis && (
                    <div>
                      <strong>解析：</strong>
                      <div style={{ marginTop: 4 }}>{question.analysis}</div>
                    </div>
                  )}
                </Card>
              )}
            />
          </div>
        )}
      </div>
    </Modal>
  );
};

export default AIGenerationModal;
